// StatsFragment.java
package com.example.tomatotodo;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.tomatotodo.api.ApiClient;
import com.example.tomatotodo.api.ApiService;
import com.example.tomatotodo.model.Result;
import com.example.tomatotodo.model.TodoRecordSyncDTO;
import com.example.tomatotodo.ui.StatsChartView;
import com.example.tomatotodo.util.RecordUtil;
import com.example.tomatotodo.util.TokenManager;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.datepicker.CalendarConstraints;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Response;

public class StatsFragment extends Fragment {
    private static final String TAG = "StatsFragment";
    private static final String PREFS_NAME = "focus_records_prefs";
    private static final String RECORDS_KEY = "focus_records";
    private static final LocalDate MIN_DATE = LocalDate.of(2024, 1, 1);

    private TextView tvTotalFocusCount;
    private TextView tvCompletedFocusCount;
    private TextView tvFailedFocusCount;
    private TextView tvTotalFocusDuration;
    private TextView tvTotalDuration;
    private MaterialButton btnStartDate;
    private MaterialButton btnEndDate;
    private SwitchMaterial switchCountNoTimer;
    private SwitchMaterial switchEnableHistory;
    private MaterialButton btnApplyFilter;
    private StatsChartView statsChartView;
    private ProgressBar progressBar; // 添加进度条

    private LocalDate startDate;
    private LocalDate endDate;

    // 默认未登录状态
    private boolean isLoggedIn = false;

    // 添加 ExecutorService 用于替代 AsyncTask
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    // 临时添加
    Button generateRecordsButton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_stats, container, false);

        initViews(view);
        isLoggedIn = TokenManager.isLoggedIn(requireContext()); // 正确设置isLoggedIn变量
        setupDefaultDateRange();
        setupClickListeners();
        updateHistorySwitchVisibility();
        loadStatsData();

        return view;
    }

    private void initViews(View view) {
        tvTotalFocusCount = view.findViewById(R.id.tv_total_focus_count);
        tvCompletedFocusCount = view.findViewById(R.id.tv_completed_focus_count);
        tvFailedFocusCount = view.findViewById(R.id.tv_failed_focus_count);
        tvTotalFocusDuration = view.findViewById(R.id.tv_total_focus_duration);
        tvTotalDuration = view.findViewById(R.id.tv_total_duration);
        btnStartDate = view.findViewById(R.id.btn_start_date);
        btnEndDate = view.findViewById(R.id.btn_end_date);
        switchCountNoTimer = view.findViewById(R.id.switch_count_no_timer);
        switchEnableHistory = view.findViewById(R.id.switch_enable_history);
        btnApplyFilter = view.findViewById(R.id.btn_apply_filter);
        statsChartView = view.findViewById(R.id.stats_chart_view);
        progressBar = new ProgressBar(requireContext()); // 初始化进度条

        // 临时添加"生成记录"按钮
        generateRecordsButton = view.findViewById(R.id.btn_generate_test_data);
    }

    /**
     * 设置默认的日期范围（最近7天）
     */
    private void setupDefaultDateRange() {
        // 默认显示最近7天的数据
        endDate = LocalDate.now();
        startDate = endDate.minusDays(6);
        updateDateButtons();
    }

    /**
     * 更新日期按钮上显示的文本
     */
    private void updateDateButtons() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        btnStartDate.setText(startDate.format(formatter));
        btnEndDate.setText(endDate.format(formatter));
    }

    /**
     * 设置各种点击监听器
     */
    private void setupClickListeners() {
        btnStartDate.setOnClickListener(v -> showDatePicker(true));
        btnEndDate.setOnClickListener(v -> showDatePicker(false));
        btnApplyFilter.setOnClickListener(v -> loadStatsData());
        switchCountNoTimer.setOnCheckedChangeListener((buttonView, isChecked) -> loadStatsData());
        switchEnableHistory.setOnCheckedChangeListener((buttonView, isChecked) -> loadStatsData());

        generateRecordsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 临时添加，生成测试数据
                com.example.tomatotodo.util.GenerateTestDataUtil.generateAndSaveTestRecords(getActivity());
            }
        });

    }

    /**
     * 显示日期选择器
     *
     * @param isStartDate true表示设置开始日期，false表示设置结束日期
     */
    private void showDatePicker(boolean isStartDate) {
        LocalDate currentDate = isStartDate ? startDate : endDate;

        MaterialDatePicker<Long> datePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("选择日期")
                .setSelection(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli())
                .setCalendarConstraints(
                        new CalendarConstraints.Builder()
                                .setStart(MIN_DATE.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli())
                                .setEnd(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli())
                                .build())
                .build();

        datePicker.addOnPositiveButtonClickListener(selection -> {
            LocalDate selectedDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(selection), ZoneId.systemDefault()).toLocalDate();
            if (isStartDate) {
                startDate = selectedDate;
            } else {
                endDate = selectedDate;
            }
            updateDateButtons();
        });

        datePicker.show(getParentFragmentManager(), "date_picker");
    }

    /**
     * 更新历史记录开关的可见性
     */
    private void updateHistorySwitchVisibility() {
        switchEnableHistory.setVisibility(isLoggedIn ? View.VISIBLE : View.GONE);
    }

    /**
     * 加载统计数据并显示在UI上
     */
    private void loadStatsData() {
        List<TodoRecordSyncDTO> records = new ArrayList<>();

        if (switchEnableHistory.isChecked() && isLoggedIn) {
            // 如果启用了历史记录并且用户已登录，从后端获取数据
            Log.i(TAG, "启用云记录统计");
            loadRecordsFromServerAsync();
        } else {
            // 未登录，从本地SharedPreferences获取数据
            records = loadRecordsFromPreferences();
            processLoadedData(records);
        }
    }

    /**
     * 异步从服务器加载记录数据
     */
    private void loadRecordsFromServerAsync() {
        // 显示加载进度
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                // 禁用开关以防止重复点击
                switchEnableHistory.setEnabled(false);
                btnApplyFilter.setEnabled(false);
                Toast.makeText(getActivity(), "正在加载云端数据...", Toast.LENGTH_SHORT).show();
            });
        }

        executorService.execute(() -> {
            List<TodoRecordSyncDTO> records = loadRecordsFromServer();
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    processLoadedData(records);
                    // 恢复控件状态
                    switchEnableHistory.setEnabled(true);
                    btnApplyFilter.setEnabled(true);
                });
            }
        });
    }

    private void processLoadedData(List<TodoRecordSyncDTO> records) {
        // 过滤指定时间范围内的记录
        List<TodoRecordSyncDTO> filteredRecords = filterRecordsByDateRange(records);

        // 计算统计数据
        calculateAndDisplayStats(filteredRecords);

        // 更新图表数据
        updateChartData(filteredRecords);
    }

    /**
     * 从服务器加载记录数据
     */
    private List<TodoRecordSyncDTO> loadRecordsFromServer() {
        String token = TokenManager.getToken(requireContext());
        if (token == null || token.isEmpty()) {
            // 如果没有token，回退到本地数据
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    switchEnableHistory.setChecked(false);
                    Toast.makeText(getActivity(), "未登录，已切换到本地数据", Toast.LENGTH_SHORT).show();
                });
            }
            return loadRecordsFromPreferences();
        }

        // 将日期转换为字符串格式
        String startDateStr = startDate.toString(); // 格式为 yyyy-MM-dd
        String endDateStr = endDate.toString();     // 格式为 yyyy-MM-dd

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<Result<List<TodoRecordSyncDTO>>> call = apiService.queryRecords(token, startDateStr, endDateStr);

        try {
            Response<Result<List<TodoRecordSyncDTO>>> response = call.execute();
            if (response.isSuccessful() && response.body() != null) {
                Result<List<TodoRecordSyncDTO>> result = response.body();
                if (result.getCode() == 200) {
                    List<TodoRecordSyncDTO> records = result.getData();
                    if (records != null) {
                        // 日志展示数据详情
                        Log.d(TAG, "服务器返回的记录数据: " + records);
                        // 添加详细日志来查看每条记录的时间字段
                        for (int i = 0; i < records.size(); i++) {
                            TodoRecordSyncDTO record = records.get(i);
                            Log.d(TAG, "记录 " + i + ": clientCreatedAt=" + record.getClientCreatedAt() +
                                    ", startTime=" + record.getStartTime() +
                                    ", endTime=" + record.getEndTime());
                        }
                        return records;
                    } else {
                        Log.e(TAG, "服务器返回的记录数据为空");
                    }
                } else {
                    Log.e(TAG, "服务器返回错误: " + result.getMessage());
                }
            } else {
                Log.e(TAG, "网络请求失败，响应码: " + response.code());
            }
        } catch (Exception e) {
            Log.e(TAG, "网络请求异常", e);
        }

        // 提示网络异常
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                switchEnableHistory.setChecked(false);
                Toast.makeText(getActivity(), "网络异常或超时，已切换到本地数据", Toast.LENGTH_LONG).show();
            });
        }

        // 出现任何问题都回退到本地数据
        Log.w(TAG, "回退到本地数据");
        return loadRecordsFromPreferences();
    }

    private void updateChartData(List<TodoRecordSyncDTO> records) {
        Log.i(TAG, "更新图表数据");
        statsChartView.setDateRange(startDate, endDate);
        statsChartView.setData(records);
    }

    /**
     * 从SharedPreferences加载记录数据
     *
     * @return 包含所有记录的列表
     */
    private List<TodoRecordSyncDTO> loadRecordsFromPreferences() {
        SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, getActivity().MODE_PRIVATE);
        String recordsJson = prefs.getString(RECORDS_KEY, "[]");
        Log.d(TAG, "从SharedPreferences加载记录: " + recordsJson);

        // 使用RecordUtil中配置的Gson实例来正确处理LocalDateTime
        Gson gson = RecordUtil.getGsonInstance();
        Type listType = new TypeToken<List<TodoRecordSyncDTO>>() {
        }.getType();
        List<TodoRecordSyncDTO> records = gson.fromJson(recordsJson, listType);

        if (records == null) {
            records = new ArrayList<>();
        }

        return records;
    }

    /**
     * 根据日期范围过滤记录
     *
     * @param records 要过滤的记录列表
     * @return 过滤后的记录列表
     */
    private List<TodoRecordSyncDTO> filterRecordsByDateRange(List<TodoRecordSyncDTO> records) {
        List<TodoRecordSyncDTO> filteredRecords = new ArrayList<>();

        // 检查日期范围是否有效
        if (startDate == null || endDate == null) {
            Log.w(TAG, "日期范围未设置，返回所有记录");
            return new ArrayList<>(records);
        }

        Log.d(TAG, "开始过滤记录，日期范围: " + startDate + " 至 " + endDate + "，总记录数: " + records.size());

        for (int i = 0; i < records.size(); i++) {
            TodoRecordSyncDTO record = records.get(i);
            LocalDateTime timeToCheck = record.getEffectiveTime();

            Log.d(TAG, "检查记录 " + i + ": 用于比较的时间=" + timeToCheck);

            if (timeToCheck != null) {
                LocalDate dateToCheck = timeToCheck.toLocalDate();
                Log.d(TAG, "记录 " + i + " 的日期: " + dateToCheck);
                // 检查记录是否在选定的时间范围内
                if (!dateToCheck.isBefore(startDate) && !dateToCheck.isAfter(endDate)) {
                    Log.d(TAG, "记录 " + i + " 在时间范围内，添加到结果中");
                    filteredRecords.add(record);
                } else {
                    Log.d(TAG, "记录 " + i + " 不在时间范围内，已忽略");
                }
            } else {
                // 忽略有问题的记录并记录日志
                Log.w(TAG, "记录的时间字段都为null，已忽略，记录详情: " + record);
            }
        }

        Log.d(TAG, "过滤后得到 " + filteredRecords.size() + " 条记录");
        return filteredRecords;
    }

    /**
     * 计算统计数据并显示在UI上
     *
     * @param records 需要统计的记录列表
     */
    private void calculateAndDisplayStats(List<TodoRecordSyncDTO> records) {
        int totalFocusCount = 0;
        int completedFocusCount = 0;
        int failedFocusCount = 0;
        int totalFocusSeconds = 0;
        int totalSeconds = 0;

        boolean countNoTimerRecords = switchCountNoTimer.isChecked();

        for (TodoRecordSyncDTO record : records) {
            // 判断是否为不计时记录：已完成并且结束时间比开始时间早
            boolean isNoTimerRecord = Boolean.TRUE.equals(record.getFinished())
                    && record.getEndTime() != null
                    && record.getStartTime() != null
                    && record.getEndTime().isBefore(record.getStartTime());

            // 根据设置决定是否将不计时记录计入次数统计
            if (isNoTimerRecord && !countNoTimerRecords) {
                // 不计时记录且设置为不计入，则跳过次数统计
            } else {
                totalFocusCount++;

                if (Boolean.TRUE.equals(record.getFinished())) {
                    completedFocusCount++;
                } else {
                    failedFocusCount++;
                }
            }

            // 只有非不计时记录才计入时长统计
            if (!isNoTimerRecord) {
                totalFocusSeconds += record.getActualFocusSeconds() != null ? record.getActualFocusSeconds() : 0;
                int focusSeconds = record.getActualFocusSeconds() != null ? record.getActualFocusSeconds() : 0;
                int restSeconds = record.getActualRestSeconds() != null ? record.getActualRestSeconds() : 0;
                totalSeconds += focusSeconds + restSeconds;
            }
        }

        // 更新UI显示
        tvTotalFocusCount.setText(String.valueOf(totalFocusCount));
        tvCompletedFocusCount.setText(String.valueOf(completedFocusCount));
        tvFailedFocusCount.setText(String.valueOf(failedFocusCount));
        tvTotalFocusDuration.setText(formatDuration(totalFocusSeconds));
        tvTotalDuration.setText(formatDuration(totalSeconds));

        Log.d(TAG, "统计数据计算完成: 总次数=" + totalFocusCount + ", 完成=" + completedFocusCount + ", 失败=" + failedFocusCount);
    }

    /**
     * 将秒数格式化为小时和分钟的字符串
     *
     * @param seconds 总秒数
     * @return 格式化后的时间字符串
     */
    private String formatDuration(int seconds) {
        if (seconds <= 0) {
            return "0小时0分钟";
        }

        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;

        if (hours > 0) {
            return hours + "小时" + minutes + "分钟";
        } else {
            return minutes + "分钟";
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理图表资源避免内存泄漏
        if (statsChartView != null) {
            statsChartView.clear();
        }
        // 关闭 ExecutorService
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
}
